import axios from "axios";
import NProgress from "nprogress";
import { Notification } from "element-ui";

const service = axios.create({
  baseURL: process.env.VUE_APP_API,
  timeout: 10 * 60 * 1000
});

service.defaults.headers["Content-type"] = "application/json";
service.interceptors.request.use(
  config => {
    function getCookie(name) { //获取指定名称的cookie值
      // (^| )name=([^;]*)(;|$),match[0]为与整个正则表达式匹配的字符串，match[i]为正则表达式捕获数组相匹配的数组；
      var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
      if(arr != null) {
        // console.log(arr);
        return unescape(arr[2]);
      }
      return null;
      }
      const token=getCookie('stuToken'); //cookie赋值给变量。      
    // const token = document.cookie.substring(9)
    // const token = JSON.parse(localStorage.getItem('user')).data.token
    config.headers["token"] = token || "";
    // config.headers["token"] = "gbrUBoCwQ21LpX9VihliYg==";
    NProgress.start();
    return config;
  },
  err => {
    console.log("request reject:", err);
    NProgress.done();
    return Promise.resolve(err);
  }
);

service.interceptors.response.use(
  res => {
    NProgress.done();
    //no login in
    if (res.data.code === 1500) {
      // store.state.user !== null &&
        Notification.error("当前登录用户过期,请重新登录!");
      // store.dispatch("exitLogin");
      return;
    }
    //download file request
    if (res.status === 200 && res.data instanceof Blob) return res.data;
    //normal request
    if (res.data.code === 0) {
      // if (res.data.data === null) return {};
      return res.data.data;
    }
    Notification.error(res.data.msg);//
    console.table({ api: res.config.url, ...res.data });
    return Promise.reject(res.data.msg);
  },
  err => {
    NProgress.done();
    return Promise.reject(err);}

);

export default service;
